<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>脚本管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 300;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.8;
        }

        .main-content {
            display: flex;
            min-height: 70vh;
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-right: 1px solid #e9ecef;
            padding: 20px;
        }

        .sidebar h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 1.3em;
        }

        .script-list {
            list-style: none;
        }

        .script-item {
            background: white;
            margin-bottom: 10px;
            padding: 15px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            border-left: 4px solid #3498db;
        }

        .script-item:hover {
            background: #3498db;
            color: white;
            transform: translateX(5px);
        }

        .script-item.active {
            background: #2980b9;
            color: white;
        }

        .terminal-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .controls {
            padding: 20px;
            background: #ecf0f1;
            border-bottom: 1px solid #bdc3c7;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn-primary {
            background: #27ae60;
            color: white;
        }

        .btn-primary:hover {
            background: #229954;
            transform: translateY(-2px);
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }

        .btn:disabled {
            background: #95a5a6;
            cursor: not-allowed;
            transform: none;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        .input-field {
            flex: 1;
            padding: 12px;
            border: 2px solid #bdc3c7;
            border-radius: 6px;
            font-size: 14px;
        }

        .input-field:focus {
            outline: none;
            border-color: #3498db;
        }

        .terminal {
            height: 650px;
            background: #1e1e1e;
            color: #ffffff;
            font-family: 'Courier New', monospace;
            padding: 20px;
            overflow-y: auto;
            white-space: pre-wrap;
            line-height: 1.4;
        }

        .terminal::-webkit-scrollbar {
            width: 8px;
        }

        .terminal::-webkit-scrollbar-track {
            background: #2c2c2c;
        }

        .terminal::-webkit-scrollbar-thumb {
            background: #555;
            border-radius: 4px;
        }

        .terminal::-webkit-scrollbar-thumb:hover {
            background: #777;
        }

        .output-line {
            margin: 2px 0;
        }

        .error-line {
            color: #e74c3c;
        }

        .success-line {
            color: #27ae60;
        }

        .info-line {
            color: #3498db;
        }

        .status {
            padding: 10px 20px;
            background: #34495e;
            color: white;
            font-size: 14px;
        }

        .status.connected {
            background: #27ae60;
        }

        .status.error {
            background: #e74c3c;
        }

        .script-preview {
            margin-top: 15px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .script-preview h4 {
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .script-content {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
            }
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="header">
                <h1>🚀 脚本管理系统</h1>
                <p>在线执行和交互式Python脚本管理平台</p>
            </div>

            <div class="main-content">
                <div class="sidebar">
                    <h3>📁 可用脚本</h3>
                    <ul class="script-list">
                        <li v-for="script in scripts" :key="script.name"
                            :class="['script-item', { active: selectedScript === script.name }]"
                            @click="selectScript(script.name)">
                            {{ script.name }}
                        </li>
                    </ul>

                    <div v-if="selectedScript" class="script-preview">
                        <h4>脚本预览</h4>
                        <div class="script-content">{{ scriptContent }}</div>
                    </div>
                </div>

                <div class="terminal-area">
                    <div class="controls">
                        <div class="btn-group">
                            <button class="btn btn-primary" @click="startScript"
                                :disabled="!selectedScript || isRunning">
                                ▶️ 执行脚本
                            </button>
                            <button class="btn btn-danger" @click="terminateScript" :disabled="!isRunning">
                                ⏹️ 终止脚本
                            </button>
                        </div>

                        <div class="input-group">
                            <input v-model="userInput" @keyup.enter="sendInput" :disabled="!isRunning"
                                class="input-field" placeholder="输入内容并按回车发送...">
                            <button class="btn btn-primary" @click="sendInput"
                                :disabled="!isRunning || !userInput.trim()">
                                📤 发送
                            </button>
                        </div>
                    </div>

                    <div class="terminal" ref="terminal">
                        <div v-for="(line, index) in terminalOutput" :key="index" :class="['output-line', line.type]">
                            {{ line.content }}
                        </div>
                        <div v-if="terminalOutput.length === 0" class="info-line">
                            请选择一个脚本并点击"执行脚本"开始...
                        </div>
                    </div>

                    <div :class="['status', connectionStatus.class]">
                        {{ connectionStatus.text }}
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    scripts: [],
                    selectedScript: null,
                    scriptContent: '',
                    terminalOutput: [],
                    userInput: '',
                    isRunning: false,
                    websocket: null,
                    sessionId: null,
                    connectionStatus: {
                        text: '未连接',
                        class: ''
                    }
                }
            },

            async mounted() {
                await this.loadScripts();
                this.generateSessionId();
                this.connectWebSocket();
            },

            methods: {
                generateSessionId() {
                    this.sessionId = 'session_' + Math.random().toString(36).substr(2, 9);
                },

                async loadScripts() {
                    try {
                        const response = await fetch('http://localhost:8000/api/scripts');
                        const data = await response.json();
                        this.scripts = data.scripts;
                    } catch (error) {
                        this.addOutput('加载脚本列表失败: ' + error.message, 'error-line');
                    }
                },

                async selectScript(scriptName) {
                    this.selectedScript = scriptName;
                    try {
                        const response = await fetch(`http://localhost:8000/api/script/${scriptName}`);
                        const data = await response.json();
                        this.scriptContent = data.content;
                    } catch (error) {
                        this.scriptContent = '无法加载脚本内容';
                    }
                },

                connectWebSocket() {
                    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                    const wsUrl = `${protocol}//localhost:8000/ws/${this.sessionId}`;

                    this.websocket = new WebSocket(wsUrl);

                    this.websocket.onopen = () => {
                        this.addOutput('WebSocket连接已建立', 'success-line');
                        this.connectionStatus = {
                            text: '已连接',
                            class: 'connected'
                        };
                    };

                    this.websocket.onmessage = (event) => {
                        const message = JSON.parse(event.data);
                        this.handleWebSocketMessage(message);
                    };

                    this.websocket.onclose = () => {
                        this.connectionStatus = {
                            text: '连接已断开',
                            class: 'error'
                        };
                        this.isRunning = false;
                    };

                    this.websocket.onerror = (error) => {
                        this.connectionStatus = {
                            text: '连接错误',
                            class: 'error'
                        };
                        this.addOutput('WebSocket错误: ' + error.message, 'error-line');
                    };
                },

                handleWebSocketMessage(message) {
                    switch (message.type) {
                        case 'started':
                            this.addOutput(message.message, 'success-line');
                            this.isRunning = true;
                            break;
                        case 'output':
                            this.addOutput(message.data, '');
                            break;
                        case 'finished':
                            this.addOutput(`\n脚本执行完成，退出码: ${message.return_code}`, 'info-line');
                            this.isRunning = false;
                            break;
                        case 'error':
                            this.addOutput(message.message, 'error-line');
                            break;
                        case 'terminated':
                            this.addOutput(message.message, 'info-line');
                            this.isRunning = false;
                            break;
                    }
                },

                addOutput(content, className) {
                    this.terminalOutput.push({
                        content: content,
                        type: className
                    });

                    this.$nextTick(() => {
                        const terminal = this.$refs.terminal;
                        terminal.scrollTop = terminal.scrollHeight;
                    });
                },

                startScript() {
                    if (!this.selectedScript) {
                        alert('请先选择一个脚本');
                        return;
                    }

                    if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
                        this.addOutput('WebSocket连接未建立，请等待连接后重试', 'error-line');
                        return;
                    }

                    this.terminalOutput = [];
                    this.addOutput(`正在执行脚本: ${this.selectedScript}`, 'info-line');

                    this.websocket.send(JSON.stringify({
                        type: 'start_script',
                        script_name: this.selectedScript
                    }));
                },

                sendInput() {
                    if (!this.userInput.trim() || !this.isRunning) return;

                    this.addOutput(`> ${this.userInput}`, 'info-line');

                    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                        this.websocket.send(JSON.stringify({
                            type: 'input',
                            data: this.userInput
                        }));
                    }

                    this.userInput = '';
                },

                terminateScript() {
                    if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
                        this.websocket.send(JSON.stringify({
                            type: 'terminate'
                        }));
                    }
                    this.isRunning = false;
                }
            }
        }).mount('#app');
    </script>
</body>

</html>